package com.suzhe.ymall.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suzhe.ymall.common.pojo.ApiResEntity;
import com.suzhe.ymall.system.param.SysRoleQueryParam;
import com.suzhe.ymall.system.pojo.SysRole;
import com.suzhe.ymall.system.pojo.SysRoleResource;
import com.suzhe.ymall.system.service.ISysRoleResourceService;
import com.suzhe.ymall.system.service.ISysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色 前端控制器
 * </p>
 *
 * @author suzhe
 * @since 2019-06-05
 */
@RestController
@RequestMapping("/sys/role")
@Slf4j
public class SysRoleController {

    @Autowired
    ISysRoleService iSysRoleService;

    @Autowired
    ISysRoleResourceService iSysRoleResourceService;


    @GetMapping("/list")
    public ApiResEntity list(SysRoleQueryParam sysRoleParam) {

        Integer pageNo = sysRoleParam.getPageNo();
        Integer pageSize = sysRoleParam.getPageSize();
        IPage<SysRole> page = iSysRoleService.page(new Page<>(pageNo, pageSize));

        return ApiResEntity.ok(page);
    }

    @GetMapping("/listAll")
    public ApiResEntity listAll() {
        List<SysRole> list = iSysRoleService.list();
        return ApiResEntity.ok(list);
    }

    @PostMapping("/save")
    public ApiResEntity save(@RequestBody SysRole sysRole) {
        log.debug("sysRole:{}", sysRole);
        iSysRoleService.saveSysRole(sysRole);

        return ApiResEntity.ok();
    }


    @GetMapping("/resources/{roleId}")
    public ApiResEntity listRoleResrouce(@PathVariable Integer roleId) {
        List<SysRoleResource> resources = iSysRoleResourceService.list(new QueryWrapper<SysRoleResource>()//
                .eq("role_id", roleId));
        List<Integer> rerouceIds = resources.stream() //
                .map(item -> item.getResourceId()) //
                .collect(Collectors.toList());
        return ApiResEntity.ok(rerouceIds);
    }

    @DeleteMapping("/del/{id}")
    public ApiResEntity del(@PathVariable Long id) {
        iSysRoleService.removeById(id);
        return ApiResEntity.ok();
    }

}
